
package ctrFinanceiro.gui;
import java.awt.FontMetrics;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.List;

import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListSelectionModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.border.BevelBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import ctrFinanceiro.bd.CategoriaBD;
import ctrFinanceiro.bd.ContaBD;
import ctrFinanceiro.dmp.Categoria;
import ctrFinanceiro.dmp.Conta;
import ctrFinanceiro.dmp.Usuario;
import ctrFinanceiro.gui.grid.ColumnModelConta;
import ctrFinanceiro.gui.grid.TableModelConta;

public class ContaGUI extends JInternalFrame implements MouseListener {

	private static final long serialVersionUID = 1L;

	private ContaBD bd;
	private CategoriaBD categoriaBD;
	private JPanel jContentPane = null;

	private JLabel jLabelIdConta = null;
	private JTextField jTextFieldIdConta = null;

	private JLabel jLabelDescricaoConta = null;
	private JTextField jTextFieldDescricaoConta = null;

	private JScrollPane jScrollPaneContas = null;
	private JTable tabela = null;
	private JButton jButtonIncluir = null;
	private JButton jButtonAlterar = null;
	private JButton jButtonExcluir = null;
	private JButton jButtonNovo = null;

	private JComboBox<Categoria> jComboBoxCategoria = null;


	public ContaGUI() {
		super("Cadastro de Contas",
		        false, //resizable
		        true, //closable
		       false, //maximizable
		        true);//iconifiable  

		initialize();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.bd = new ContaBD();
		this.categoriaBD = new CategoriaBD();
		this.setSize(747, 354);
		this.setContentPane(getJContentPane());
		this.inicializarCombo();
		this.inicializarTabela();
		this.setVisible(true);
	}

	public JComboBox<Categoria> getJComboBoxCategoria() {
		if (jComboBoxCategoria == null) {
			jComboBoxCategoria = new JComboBox<Categoria>();
			jComboBoxCategoria.setBounds(94, 202, 556, 20);
			// jComboBoxCategoria.addItemListener(this);
		}
		return jComboBoxCategoria;
	}

	private JLabel getJLabelNomeConta() {
		if (jLabelDescricaoConta == null) {
			jLabelDescricaoConta = new JLabel();
			jLabelDescricaoConta.setBounds(94, 157, 48, 16);
			jLabelDescricaoConta.setText("Conta");
		}
		return jLabelDescricaoConta;
	}

	private JLabel getJLabelIdConta() {
		if (jLabelIdConta == null) {
			jLabelIdConta = new JLabel();
			jLabelIdConta.setBounds(10, 157, 26, 16);
			jLabelIdConta.setText("Id:");
		}
		return jLabelIdConta;
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setLayout(null);
			jContentPane.add(getJTextFieldIdConta(), null);
			jContentPane.add(getJTextFieldNomeConta(), null);
			jContentPane.add(getJButtonIncluir(), null);
			jContentPane.add(getJButtonAlterar(), null);
			jContentPane.add(getJButtonExcluir(), null);
			jContentPane.add(getJButtonNovo(), null);

			JPanel panel = new JPanel();
			panel.setBorder(new BevelBorder(BevelBorder.RAISED, null, null,
					null, null));
			panel.setBounds(29, 11, 662, 259);
			panel.setLayout(null);

			JLabel lblCategoria = new JLabel("Categoria");
			lblCategoria.setBounds(10, 205, 83, 14);
			panel.add(lblCategoria);

			panel.add(getJComboBoxCategoria());
			panel.add(getJLabelIdConta());
			panel.add(getJLabelNomeConta());
			panel.add(getJScrollPaneContas());
			jContentPane.add(panel);
		}
		return jContentPane;
	}

	/**
	 * This method initializes jTextFieldIdConta
	 * 
	 * @return javax.swing.JTextField
	 */
	private JTextField getJTextFieldIdConta() {
		if (jTextFieldIdConta == null) {
			jTextFieldIdConta = new JTextField();
			jTextFieldIdConta.setEditable(false);
			jTextFieldIdConta.setBounds(new Rectangle(39, 185, 62, 20));
		}
		return jTextFieldIdConta;
	}

	/**
	 * This method initializes jTextFieldNomeConta
	 * 
	 * @return javax.swing.JTextField
	 */
	private JTextField getJTextFieldNomeConta() {
		if (jTextFieldDescricaoConta == null) {
			jTextFieldDescricaoConta = new JTextField();
			jTextFieldDescricaoConta
					.setBounds(new Rectangle(123, 185, 556, 20));
		}
		return jTextFieldDescricaoConta;
	}

	/**
	 * This method initializes jScrollPaneConta
	 * 
	 * @return javax.swing.JScrollPane
	 */
	private JScrollPane getJScrollPaneContas() {
		if (jScrollPaneContas == null) {
			jScrollPaneContas = new JScrollPane();
			jScrollPaneContas.setBounds(10, 11, 640, 139);
			jScrollPaneContas.setViewportView(getTabela());
		}
		return jScrollPaneContas;
	}

	/**
	 * This method initializes jListConta
	 * 
	 * @return javax.swing.JList
	 */
	private JTable getTabela() {
		if (tabela == null) {
			tabela = new JTable();
		}
		return tabela;
	}

	/**
	 * This method initializes jButtonIncluir
	 * 
	 * @return javax.swing.JButton
	 */
	private JButton getJButtonIncluir() {
		if (jButtonIncluir == null) {
			jButtonIncluir = new JButton();
			jButtonIncluir.setBounds(new Rectangle(64, 281, 102, 24));
			jButtonIncluir.setText("Incluir");
			jButtonIncluir.addMouseListener(this);
		}
		return jButtonIncluir;
	}

	/**
	 * This method initializes jButtonAlterar
	 * 
	 * @return javax.swing.JButton
	 */
	private JButton getJButtonAlterar() {
		if (jButtonAlterar == null) {
			jButtonAlterar = new JButton();
			jButtonAlterar.setBounds(new Rectangle(230, 281, 102, 24));
			jButtonAlterar.setText("Alterar");
			jButtonAlterar.addMouseListener(this);
		}
		return jButtonAlterar;
	}

	/**
	 * This method initializes jButtonExcluir
	 * 
	 * @return javax.swing.JButton
	 */
	private JButton getJButtonExcluir() {
		if (jButtonExcluir == null) {
			jButtonExcluir = new JButton();
			jButtonExcluir.setBounds(new Rectangle(396, 281, 102, 24));
			jButtonExcluir.setText("Excluir");
			jButtonExcluir.addMouseListener(this);
		}
		return jButtonExcluir;
	}

	/**
	 * This method initializes jButtonLimpar
	 * 
	 * @return javax.swing.JButton
	 */
	private JButton getJButtonNovo() {
		if (jButtonNovo == null) {
			jButtonNovo = new JButton();
			jButtonNovo.setBounds(new Rectangle(562, 281, 102, 24));
			jButtonNovo.setText("Novo");
			jButtonNovo.addMouseListener(this);
		}
		return jButtonNovo;
	}

	public void mouseClicked(MouseEvent e) {
		if (e.getSource() == this.getJButtonIncluir()) {
			if (this.getJTextFieldNomeConta().getText().isEmpty()) {
	            JOptionPane.showMessageDialog(null, "A descrição da conta é obrigatória");
	        }else if(jComboBoxCategoria.getSelectedItem() == null){
	        	JOptionPane.showMessageDialog(null, "A categoria é obrigatória");
	        }else{
	        	handlerConta("INCLUIR");
	        }
		} else if(e.getSource() == this.getJButtonAlterar()) {
			handlerConta("ALTERAR");
		} else if(e.getSource() == this.getJButtonExcluir()) {
			 int response = JOptionPane.showConfirmDialog(null, "Tem certeza que deseja excluir?", "Excluir",
				        JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

			 if (response == JOptionPane.YES_OPTION) {
				 handlerConta("EXCLUIR");
			 }
			 
		} else {
			clearFields();
		}
	}

	public void mouseEntered(MouseEvent e) {
	}

	public void mouseExited(MouseEvent e) {
	}

	public void mousePressed(MouseEvent e) {
	}

	public void mouseReleased(MouseEvent e) {
	}

	private void handlerConta(String action) {
		Conta conta = new Conta();
		Usuario usuario = UsuarioLogado.getInstance().getUsuario();
		Categoria categoria = (Categoria) jComboBoxCategoria.getSelectedItem();
		String descricao = this.getJTextFieldNomeConta().getText();
		Integer id = null;
		if (!getJTextFieldIdConta().getText().trim().isEmpty()){
			id = Integer.parseInt(this.getJTextFieldIdConta().getText());
		}
		conta.setIdCta(id);
		conta.setDescricao(descricao);
		conta.setCategoria(categoria);
		conta.setUsuario(usuario);

		if (action.equals("INCLUIR")) {
			bd.addConta(conta);
			clearFields();
		} else if (action.equals("ALTERAR")) {
			bd.updateConta(conta);
			clearFields();
		} else if (action.equals("EXCLUIR")) {
			bd.excludeConta(conta);
			clearFields();
		} else if (action.equals("NOVO")) {
			clearFields();
		}
		inicializarTabela();

	}

	private void inicializarTabela() {
		tabela.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		tabela.setModel(new TableModelConta(bd.getContas()));

		// ajuda a identificar a tabela no listner
		tabela.setSelectionModel(new DefaultListSelectionModel() {

			private static final long serialVersionUID = 1L;

			public String toString() {
				return "tabela";
			}
		});
		tabela.getSelectionModel().addListSelectionListener(
				new MyTableListener());
		tabela.setAutoCreateColumnsFromModel(false);
		FontMetrics fm = tabela.getFontMetrics(tabela.getFont());
		tabela.setColumnModel(new ColumnModelConta(fm));
		tabela.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

	}
	
	private void inicializarCombo(){
        List<Categoria> categorias = categoriaBD.getCategorias();
        for(Categoria categoria : categorias){
            jComboBoxCategoria.addItem(categoria);
        }
    }
	

	private void clearFields() {
		getJTextFieldIdConta().setText("");
		getJTextFieldNomeConta().setText("");
		getJComboBoxCategoria().setSelectedItem(null);
	}
	private class MyTableListener implements ListSelectionListener {

		public void valueChanged(ListSelectionEvent e) {

			ListSelectionModel lsm = (ListSelectionModel) e.getSource();

			// Returns true if this is one of multiple change events.
			if (e.getValueIsAdjusting())
				return;

			if (!(lsm.isSelectionEmpty())) {

				if (e.getSource().toString().equals("tabela")) {

					int sr = tabela.getSelectedRow();
					Conta conta = ((TableModelConta) tabela
							.getModel()).getValues(sr);
					Categoria categoria = conta.getCategoria();
					
					jTextFieldIdConta.setText(String.valueOf(conta.getIdCta()));
					jTextFieldDescricaoConta.setText(conta.getDescricao());
					
					DefaultComboBoxModel<Categoria> comboBoxModel = (DefaultComboBoxModel<Categoria>) jComboBoxCategoria.getModel();
					comboBoxModel.setSelectedItem(categoria);

				}
			}
		}
	}
}
